using CurrentUserDemo.Api.Infrastructures.CurrentUsers;
using CurrentUserDemo.Domain.CurrentUsers;
using CurrentUserDemo.Domain.OrderServices;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(option =>
{
    option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey
    });
    option.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference()
                {
                    Id = "Bearer",
                    Type = ReferenceType.SecurityScheme
                }
            }, Array.Empty<string>()
        }
    });
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(option =>
    {
        option.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidIssuer = "ABC.COM",
            ValidateAudience = true,
            ValidAudience = "ABC",
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Symmetric Security Key"))
        };
    });
builder.Services.AddScoped<ICurrentUser, CurrentUser>();
builder.Services.AddScoped<OrderService>();
builder.Services.AddHttpContextAccessor();

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthentication();
app.UseAuthorization();
app.Map("/token", builder => builder.Run(async context =>
{
    var claims = new List<Claim>()
    {
        new Claim("sub", "TOKEN"),
        new Claim("jti", "d3420ca6-2223-4045-95a4-efd9f3b9aa62"),
        new Claim("uid", "1")
    };
    var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Symmetric Security Key"));
    var algorithm = SecurityAlgorithms.HmacSha256;
    var signingCredentials = new SigningCredentials(secretKey, algorithm);
    var expires = DateTime.Now.AddYears(1);

    var securityToken = new JwtSecurityToken(
        claims: claims,
        issuer: "ABC.COM",
        audience: "ABC",
        notBefore: DateTime.Now,
        expires: expires,
        signingCredentials: signingCredentials
    );

    var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
    var token = jwtSecurityTokenHandler.WriteToken(securityToken);
    await context.Response.WriteAsync(token);
}));
app.MapControllers();
app.Run();